package MultiThread.AlternatePrinting;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/6/21 16:54
 * 说明：设立三个线程，交替打印 a,l,i，共50次
 * 实现：Semaphore信号量法
 *      Semaphore.acquire() 请求资源，同时信号量-1
 *          此时可以执行线程内部的逻辑
 *      Semaphore.release() 释放资源，同时信号量+1
 *          此时线程被阻塞
 */

public class Semaphore {
    public static void main(String[] args) {
        final java.util.concurrent.Semaphore semaphore1 = new java.util.concurrent.Semaphore(1);
        final java.util.concurrent.Semaphore semaphore2 = new java.util.concurrent.Semaphore(0);
        final java.util.concurrent.Semaphore semaphore3 = new java.util.concurrent.Semaphore(0);

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    try {
                        semaphore1.acquire();
                        System.out.print("a");
                        semaphore2.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    try {
                        semaphore2.acquire();
                        System.out.print("l");
                        semaphore3.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    try {
                        semaphore3.acquire();
                        System.out.print("i");
                        semaphore1.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
